<?php 
namespace App\Http\Controllers\DictApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Mysql\dict\dict;

use Symfony\Component\DomCrawler\Crawler;

use Excel;	

class DictController extends Controller
{
//	use GlobalData;

	const ROUTE_PREFIX = '/api/*';

	protected $request;

	protected $curTime;

	protected $debug;


	/**
	 * 创建新的`DictController`控制器实例
	 * @param \Illuminate\Http\Request $request
	 */
	public function __construct(Request $request)
	{
		$this->request = $request;
		$this->error = [];
		$this->curTime = time();

		if(config('app.debug')) {
			$this->debug = true;
			error_reporting(E_ALL | E_STRICT);
		} else {
			$this->debug = false;
		}
	}

    public function addDict()
    {
		set_time_limit(0);
		$notList='"ABC\'s","sadistically","White House"'; //special cases
		$inList ='"commandment"';
		//$sql = "select id, english_key from dict where done=0 and not english_key like '%-%' and english_key not in ($notList)";
		$sql = "select id, english_key from dict where done=0 and not english_key like '%-%' and english_key in ($inList)";
		$wordList = dict::select($sql);
		
		foreach($wordList as $v){
			$word = trim($v->english_key);
			echo "begin to process id=".$v->id." word=$word ... </br>";
			
			$updateStr = "";
			
			$url = "http://www.iciba.com/".$word;
			$filename = "../../dict/".$word.".html";
			$html=file_get_contents($url);
			if (empty($html)){
				echo "html is empty <br>";
				continue;
			}
			
			$crawler = new Crawler($html);
			$basicDom=$crawler->filterXPath('//body/div[@class="screen"]/div[@class="container"]/div[@class="container-left"]/div[@class="js-base-info"]/div[@class="info-article info-base"]/div[@class="in-base"]');
			if (count($basicDom)==0){
				echo "basicDom is empty <br>";
				continue;
			}
			file_put_contents($filename,$html);
			
			if (mb_strpos($html,"<ul class=\"base-list switch_part\"")===false)
				continue;
			$basicMeaningList = $basicDom->filterXPath('//ul[@class="base-list switch_part"]')->children();
			//echo "count=".count($basicMeaningList)."</br>";
			$i=0;
			for($i=0;$i<count($basicMeaningList);$i++){
				$curMeaning = $basicMeaningList->eq($i);
				//var_dump($curMeaning->html());
				$curProp = '"'.$curMeaning->filterXPath('//span[@class="prop"]')->text().'"';
				$curMeaningText = '"'.addslashes(trim($curMeaning->filterXPath('//p')->text())).'"';
				//echo "curProp=$curProp  curMeaningText=$curMeaningText</br>";
				$curPropFieldName = "prop_".$i;
				$curMeaningFieldName = "chinese_".$i;
				$updateStr .= (" ".$curPropFieldName."=".$curProp.", ".$curMeaningFieldName."=".$curMeaningText."," );
			}
			
			$variantParent = $basicDom->filterXPath('//li[@class="change clearfix"]//p');
			if (count($variantParent)>0){
				$variantList = $variantParent->children();
				$variantName = array('复数'=>'plural', '过去式'=>'past_tense', '过去分词'=>'past_participle',  '现在分词' =>'present_participle','第三人称单数'=>'third_person_singular');
				$i=0;
				for($i=0;$i<count($variantList);$i++){
					$curVariant = $variantList->eq($i);
				//	echo $curVariant->text()."</br>";
					
					$curVariantChnName = $curVariant->filterXPath('//span')->text();
					$curVariantChnName = mb_substr($curVariantChnName,0,mb_strpos($curVariantChnName ,'：'));
					$curVariantEngName = $variantName[$curVariantChnName];
					$curVariantValue = '"'.$curVariant->filterXPath('//a[@class="shape"]')->text().'"';
				
					//echo "curVariantEngName=$curVariantEngName  curVariantValue=$curVariantValue</br>";
					$updateStr .= (" ".$curVariantEngName."=".$curVariantValue."," );
				}
			}
			/*
			if (mb_substr($updateStr,mb_strlen($updateStr)-1,1)==',') {
				$updateStr = mb_substr($updateStr,0, mb_strlen($updateStr)-1);
			}
			*/
			$updateStr .= " done=1 where id=".$v->id;
			
			$updateStr = "update dict SET ".$updateStr;
			echo $updateStr."</br>";
			dict::update($updateStr);

			echo "$word is done!</br>";
			
			ob_flush();flush();
			usleep(rand(1000000,2000000));
		}
		
		echo "completed!!</br>";

    }

    public function getVocabulary()
    {
		set_time_limit(0);
		
		$inputFileName = iconv('UTF-8','GB2312',"F:\\00_NLP\\英语\\Alan Beale's Core Vocabulary.xlsx");
		Excel::load($inputFileName, function($reader) {
			
			$reader = $reader->getSheet(1);
			
			$results = $reader->toArray();
			foreach($results as $row)
				foreach($row as $cell){
					$cell=trim($cell);
					if (!empty($cell)){
						$temp_r = dict::select("select * from dict where english_key=\"$cell\"");
						if (!empty($temp_r))
							;//echo "$cell exists!</br>";
						else{
							dict::select("INSERT into dict (english_key,level) VALUES (\"$cell\",10)");
							echo "$cell NOT exists and added!</br>";
						}
						ob_flush();flush();
					}
				}
	        //$data = $reader->all();
	        //dd($data);
	    });

    }
	
    public function delDup(){
		set_time_limit(0);
		$sql="select id, english_key, count(*) mycount from dict group by english_key";
		$r=dict::select($sql);
		foreach($r as $v){
			if ($v->mycount==1){
				continue;
			}
			echo "begin to process ".$v->english_key."</br>";
			$sql = "select * from dict where english_key='".addslashes($v->english_key)."' order by id";
			$r2 = dict::select($sql);
			for ($i=1;$i<count($r2);$i++){
				$sql = "delete from dict where id=".$r2[$i]->id;
				dict::delete($sql);
				echo $sql."</br>";
				ob_flush();flush();
			}
		}
		
	}

} //!- PrepDictController
?>
